package cn.yunyichina.provider.message.utils;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.message.dao.OrgAppTemplateDao;
import cn.yunyichina.provider.message.entity.OrgAppTemplate;
import cn.yunyichina.provider.message.entity.TextTemplate;
import cn.yunyichina.provider.message.entity.TmpTemplateList;
import cn.yunyichina.provider.message.service.impl.MsgServiceImpl;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Joe.zhou on 2017/12/13.
 */
public class MsgAppUtils {

    private static OrgAppTemplateDao orgAppTemplateDao = SpringContextHandler.getBean(OrgAppTemplateDao.class);

    private static MsgServiceImpl msgService = SpringContextHandler.getBean(MsgServiceImpl.class);

    private static Logger logger = LoggerFactory.getLogger(MsgAppUtils.class);

    /**
     * 获取实际应用模板
     * @param json
     * @return
     */
    public static OrgAppTemplate getOrgAppTemplat(String json){
        logger.info("MsgAppUtils.getOrgAppTemplat  json-->" + json);
        AppMessageVo appMessageVo = JsonUtils.parseObject(json, AppMessageVo.class);
        OrgAppTemplate orgAppTemplate = new OrgAppTemplate();
        orgAppTemplate.setPlatformOrgAppCode(appMessageVo.getPlatformOrgAppCode());
        orgAppTemplate.setDevOrgCode(appMessageVo.getDevOrgCode());
        orgAppTemplate.setPlatformType(appMessageVo.getPlatformType());
        orgAppTemplate.setLibraryTemplateType(appMessageVo.getLibraryTemplateType());
        orgAppTemplate.setPlatformTemplateCode(appMessageVo.getPlatformTemplateCode());
        List<OrgAppTemplate> orgAppTemplates = orgAppTemplateDao.select(orgAppTemplate);
        if(orgAppTemplates.size() < 0){
            orgAppTemplate.setDevOrgCode(null);
            orgAppTemplates = orgAppTemplateDao.select(orgAppTemplate);
        }

        return orgAppTemplates.get(0);
    }


    /**
     * 根据入参获取paymentSetting配置
     * @param appCode
     * @param orgCode
     * @param platformType
     * @return
     */
    public static PaymentSettingResponse getPaymentSettingResponse(String appCode, String orgCode, Integer platformType){
        logger.info("MsgAppUtils.getPaymentSettingResponse  param-->" + appCode + " : " + orgCode + " : " + platformType);
        return msgService.getPaymentSetting(appCode,orgCode,platformType);
    }

    /**
     * 构造新map匹配规则
     * @param map
     * @return
     */
    public static Map<String,String> getNewParamMap(Map<String,String> map){
        Map<String,String> resultMap = new HashMap<String,String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            resultMap.put("{{"+entry.getKey()+"}}" , entry.getValue());
        }
        return resultMap;
    }


    /**
     * 构造微信模板消息返回msgContent
     * @param templateLists
     * @param appMessageVo
     * @return
     */
    public static Map<String,Object> getResultWechatMsgContentMap(List<TmpTemplateList> templateLists , AppMessageVo appMessageVo){
        logger.info("MsgAppUtils.getResultWechatMsgContentMap  json-->" + JSON.toJSONString(templateLists));
        Map<String,Object> resultMap = new HashMap<String,Object>();
        //组装Wechat.content
        for (int i = 0; i < templateLists.size(); i++) {
            Map<String, String> contentMap = appMessageVo.getMsgContentMap();
            contentMap = getNewParamMap(contentMap);
            String node = templateLists.get(i).getNode();
            String value = templateLists.get(i).getValue();

            if(!value.contains("{{")){
                Map<String,String> parm = new HashMap<String,String>();
                parm.put("value" , value);  //替换后的值
                parm.put("node" , node);
                parm.put("font_color" , templateLists.get(i).getFontColour());
                resultMap.put(node , parm);
                continue;
            }

            //替换数据库value
            for (Map.Entry<String, String> entry : contentMap.entrySet()) {
                if(entry.getKey().indexOf(value) != -1){
                    String repStr = value.replace(entry.getKey(), entry.getValue());
                    Map<String,String> parm = new HashMap<String,String>();
                    parm.put("value" , repStr);  //替换后的值
                    parm.put("node" , node);
                    parm.put("font_color" , templateLists.get(i).getFontColour());
                    resultMap.put(node , parm);
                }
            }
        }
        return resultMap;
    }



    /**
     * 构造支付宝模板消息返回msgContent
     * @param templateLists
     * @param appMessageVo
     * @return
     */
    public static List<Object> getResultAlipayMsgContentMap(List<TmpTemplateList> templateLists , AppMessageVo appMessageVo){
        logger.info("MsgAppUtils.getResultAlipayMsgContentMap  json-->" + JSON.toJSONString(templateLists));
        List<Object> lists = new ArrayList<Object>();
        //组装Alipay.content
        for (int i = 0; i < templateLists.size(); i++) {
            Map<String, String> contentMap = appMessageVo.getMsgContentMap();
            contentMap = getNewParamMap(contentMap);
            String node = templateLists.get(i).getNode();
            String value = templateLists.get(i).getValue();

            if(!value.contains("{{")){
                Map<String,String> parm = new HashMap<String,String>();
                parm.put("value" , value);  //替换后的值
                parm.put("node" , node);
                parm.put("font_color" , templateLists.get(i).getFontColour());
                lists.add(parm);
                continue;
            }

            //替换数据库value
            for (Map.Entry<String, String> entry : contentMap.entrySet()) {
                if(entry.getKey().indexOf(value) != -1){
                    String repStr = value.replace(entry.getKey(), entry.getValue());
                    Map<String,String> parm = new HashMap<String,String>();
                    parm.put("value" , repStr);  //替换后的值
                    parm.put("node" , node);
                    parm.put("font_color" , templateLists.get(i).getFontColour());
                    lists.add(parm);
                }
            }
        }
        return lists;
    }


    /**
     * 构造文本消息返回msgContent
     * @param textTemplate
     * @param appMessageVo
     * @return
     */
    public static String getResultTextMsgContentStr(TextTemplate textTemplate , AppMessageVo appMessageVo){
        logger.info("MsgAppUtils.getResultTextMsgContentMap  json-->" + JSON.toJSONString(textTemplate));
        String msgContent = textTemplate.getMsgContent();
        Map<String, String> contentMap = appMessageVo.getMsgContentMap();
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            logger.info("key= " + entry.getKey() + " and value= " + entry.getValue());
            msgContent = msgContent.replaceAll("(?i)\\{\\{\\s*"+entry.getKey()+"\\s*\\}\\}", entry.getValue());
        }
        return msgContent;
    }




    public static void main(String[] args) {
        List<TmpTemplateList> templateLists = new ArrayList<>();
        TmpTemplateList tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("keyword1");
        tmpTemplateList.setValue("userName");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);

        tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("keyword2");
        tmpTemplateList.setValue("sex");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);

        tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("keyword3");
        tmpTemplateList.setValue("deptName");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);

        tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("keyword4");
        tmpTemplateList.setValue("doctorName");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);

        tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("keyword5");
        tmpTemplateList.setValue("time");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);

        tmpTemplateList = new TmpTemplateList();
        tmpTemplateList.setNode("remark");
        tmpTemplateList.setValue("remark");
        tmpTemplateList.setFontColour("black");
        templateLists.add(tmpTemplateList);
        AppMessageVo appMessageVo = new AppMessageVo();

        Map<String,String> map = new HashMap<String,String>();
        map.put("userName" , "陈淑婷");
        map.put("sex" , "女");
        map.put("deptName" , "邓宏伟");
        map.put("doctorName" , "吕小燕");
        map.put("time" , "2018-01-26 14:00-14:30");
        map.put("remark" , "排队号:130\n" +
                "订单号:YRP201801261418237415\n" +
                "发票流水号:GHCS30002975\n" +
                "登记号:GHCS30002975\n" +
                "就诊地址:3楼B区4诊室\n" +
                "就诊说明:");

        appMessageVo.setMsgContentMap(map);

        List<Object> alipayMsgContents = getResultAlipayMsgContentMap(templateLists, appMessageVo);

        System.out.println("Alipay替换成功后msg_content：" + JSON.toJSONString(alipayMsgContents));
    }
}
